from wx import wx
import wx.grid as wxgrid
import sqlite3
import AddTableDialog
import EditTableProperties

class CreateTableTab(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        
        self.toolbar_ADDTABLE = wx.NewId()
        self.toolbar_DELTABLE = wx.NewId()
        self.toolbar_ADDROW = wx.NewId()
        self.toolbar_DELROW = wx.NewId()
        self.toolbar_ADDCOL = wx.NewId()
        self.toolbar_DELCOL = wx.NewId()
        self.toolbar_UPDATETABLE = wx.NewId()
        self.toolbar_BOLDSEL = wx.NewId()
        self.toolbar_SLANTSEL = wx.NewId()
        self.toolbar_UNDERSEL = wx.NewId()
        self.toolbar_EDITPROP = wx.NewId()
        self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE))
        self.gridPanel = wx.Panel(self)
        self.tableListBox = wx.ListBox(self, -1, size=wx.Size(100, -1), style=wx.BORDER_SUNKEN | wx.LB_SINGLE | wx.LB_NEEDED_SB)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.gridPanel.SetSizer(self.sizer)
        self.tableToolbar = self.MakeTableToolbar()
        self.mainBox = wx.BoxSizer(wx.VERTICAL)
        self.botBox = wx.BoxSizer(wx.HORIZONTAL)
        self.topBox = wx.BoxSizer(wx.HORIZONTAL)
        self.topBox.Add(self.tableToolbar, 1, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.botBox.Add(self.tableListBox, 0, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.botBox.Add(self.gridPanel, 1, wx.EXPAND)
        self.mainBox.Add(self.topBox, 0, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.mainBox.Add(self.botBox, 1, wx.GROW | wx.EXPAND)
        self.SetSizer(self.mainBox)
        self.tableList = []
        
        wx.EVT_LISTBOX(self, self.tableListBox.GetId(), self.OnSelectedTableItem)
                
    def MakeTableToolbar(self):
        tb = wx.ToolBar(self, -1, style=wx.TB_FLAT | wx.NO_BORDER)
        tb.AddTool(self.toolbar_ADDTABLE, wx.Bitmap("images/list-add.png", wx.BITMAP_TYPE_PNG), shortHelpString="Add Table")
        tb.AddTool(self.toolbar_DELTABLE, wx.Bitmap("images/list-remove.png", wx.BITMAP_TYPE_PNG), shortHelpString="Remove Selected Table")
        tb.AddSeparator()
        tb.AddTool(self.toolbar_ADDROW, wx.Bitmap("images/row-add.png", wx.BITMAP_TYPE_PNG), shortHelpString="Insert Row")
        tb.AddTool(self.toolbar_DELROW, wx.Bitmap("images/row-del.png", wx.BITMAP_TYPE_PNG), shortHelpString="Delete Row")
        tb.AddTool(self.toolbar_ADDCOL, wx.Bitmap("images/col-add.png", wx.BITMAP_TYPE_PNG), shortHelpString="Insert Column")
        tb.AddTool(self.toolbar_DELCOL, wx.Bitmap("images/col-del.png", wx.BITMAP_TYPE_PNG), shortHelpString="Delete Column")
        tb.AddSeparator()
        tb.AddTool(self.toolbar_BOLDSEL, wx.Bitmap("images/format-text-bold.png", wx.BITMAP_TYPE_PNG), isToggle = True, shortHelpString="Bold")
        tb.AddTool(self.toolbar_SLANTSEL, wx.Bitmap("images/format-text-italic.png", wx.BITMAP_TYPE_PNG), isToggle = True, shortHelpString="Italic")
        tb.AddTool(self.toolbar_UNDERSEL, wx.Bitmap("images/format-text-underline.png", wx.BITMAP_TYPE_PNG), isToggle = True, shortHelpString="Underline")
        tb.AddSeparator()
        tb.AddTool(self.toolbar_EDITPROP, wx.Bitmap("images/document-properties.png", wx.BITMAP_TYPE_PNG), shortHelpString="Table Properties")
        tb.AddTool(self.toolbar_UPDATETABLE, wx.Bitmap("images/document-save.png", wx.BITMAP_TYPE_PNG), shortHelpString="Update Table Content")
        tb.EnableTool(self.toolbar_ADDTABLE, True)
        tb.EnableTool(self.toolbar_DELTABLE, False)
        tb.EnableTool(self.toolbar_ADDCOL, False)
        tb.EnableTool(self.toolbar_ADDROW, False)
        tb.EnableTool(self.toolbar_DELCOL, False)
        tb.EnableTool(self.toolbar_DELROW, False)
        tb.EnableTool(self.toolbar_BOLDSEL, False)
        tb.EnableTool(self.toolbar_SLANTSEL, False)
        tb.EnableTool(self.toolbar_UPDATETABLE, False)
        tb.EnableTool(self.toolbar_UNDERSEL, False)
        tb.EnableTool(self.toolbar_EDITPROP, False)
        
        wx.EVT_TOOL(self, self.toolbar_ADDTABLE, self.AddTable)
        wx.EVT_TOOL(self, self.toolbar_DELTABLE, self.DelTable)
        wx.EVT_TOOL(self, self.toolbar_ADDROW, self.AddRow)
        wx.EVT_TOOL(self, self.toolbar_DELROW, self.DelRow)
        wx.EVT_TOOL(self, self.toolbar_ADDCOL, self.AddCol)
        wx.EVT_TOOL(self, self.toolbar_DELCOL, self.DelCol)
        wx.EVT_TOOL(self, self.toolbar_BOLDSEL, self.BoldSelection)
        wx.EVT_TOOL(self, self.toolbar_SLANTSEL, self.SlantSelection)
        wx.EVT_TOOL(self, self.toolbar_UPDATETABLE, self.UpdateTable)
        wx.EVT_TOOL(self, self.toolbar_UNDERSEL, self.UnderSelection)
        wx.EVT_TOOL(self, self.toolbar_EDITPROP, self.EditProperties)
        
        tb.Realize()
        
        return tb
        

    def OnSelectedTableItem(self, event):
        if(self.tableListBox.GetSelection() != -1):
            self.tableToolbar.EnableTool(self.toolbar_DELTABLE, True)
            self.tableToolbar.EnableTool(self.toolbar_ADDCOL, True)
            self.tableToolbar.EnableTool(self.toolbar_ADDROW, True)
            self.tableToolbar.EnableTool(self.toolbar_DELCOL, True)
            self.tableToolbar.EnableTool(self.toolbar_DELROW, True)
            self.tableToolbar.EnableTool(self.toolbar_BOLDSEL, True)
            self.tableToolbar.EnableTool(self.toolbar_SLANTSEL, True)
            self.tableToolbar.EnableTool(self.toolbar_UNDERSEL, True)
            self.tableToolbar.EnableTool(self.toolbar_UPDATETABLE, True)
            self.tableToolbar.EnableTool(self.toolbar_EDITPROP, True)
            
            # start the function to load values
            tmpString = self.tableListBox.GetStringSelection()
            tmpString2 = tmpString.split(".", 1)
            self.TopLevelParent.DisplayDebug(self.TopLevelParent.currentTableDict[int(tmpString2[0])][0])
            self.rawtabledata = self.TopLevelParent.currentTableDict[int(tmpString2[0])][0]
            self.tableRows = self.rawtabledata.split("||")
            self.tableList[:] = []
            for row in self.tableRows:
                self.tableList.append(row.split("::"))
            if(self.gridPanel.GetChildren() != []):
                self.gridPanel.DestroyChildren()
            self.tableGrid = wxgrid.Grid(self.gridPanel)
            wxgrid.EVT_GRID_SELECT_CELL(self, self.OnSelectCell)
            self.tableGrid.CreateGrid(len(self.tableList), len(self.tableList[0]))
            self.tableGrid.SetRowLabelSize(0)
            self.tableGrid.SetColLabelSize(0)
            self.sizer.Add(self.tableGrid, 1, wx.GROW | wx.EXPAND)
            self.gridPanel.Layout()
            # need to loop over tablelist to populate grid cells.
            for i in range(0, len(self.tableList)):
                for j in range(0, len(self.tableList[i])):
                    self.tableGrid.SetCellValue(i, j, self.tableList[i][j])
            
    def AddTable(self, event):
        self.addTableDialog = AddTableDialog.AddTableDialog(self, -1, "Add Table to Course", size=(550, 200), style=wx.DEFAULT_DIALOG_STYLE)
        self.addTableDialog.CenterOnParent()
        
        if(self.addTableDialog.ShowModal() == wx.ID_OK):
            self.TopLevelParent.DisplayDebug("you pressed OK")
            self.layoutValue = self.addTableDialog.tableAltText.GetValue() + "::" + self.addTableDialog.tableCaptionText.GetValue()
            con = sqlite3.connect(self.TopLevelParent.database)
            cur = con.cursor()
            cur.execute("INSERT INTO ResourceTable(resourceTypeID, resourceData, layout, courseID) VALUES(3, '::::::::::||::::::::::||::::::::::||::::::::::||::::::::::', ?, ?)", (self.layoutValue, self.TopLevelParent.currentCourseID))
            lastID = cur.lastrowid
            con.commit()
            con.close()
            self.TopLevelParent.currentTableDict = self.TopLevelParent.RefreshListBox(self.tableListBox, self.TopLevelParent.currentCourseID, 3, None)
            if(self.gridPanel.GetChildren() != []):
                self.gridPanel.DestroyChildren()
            self.tableGrid = wxgrid.Grid(self.gridPanel)
            wxgrid.EVT_GRID_SELECT_CELL(self, self.OnSelectCell)
            self.tableGrid.CreateGrid(5, 5)
            self.tableGrid.SetRowLabelSize(0)
            self.tableGrid.SetColLabelSize(0)
            self.sizer.Add(self.tableGrid, 1, wx.GROW | wx.EXPAND)
            self.gridPanel.Layout()
            self.tableListBox.SetSelection(self.tableListBox.FindString(str(lastID) + ". " + self.addTableDialog.tableCaptionText.GetValue()))
        else:
            self.TopLevelParent.DisplayDebug("you pressed cancel")
            
        self.addTableDialog.Destroy()

    def EditProperties(self, event):
        self.TopLevelParent.DisplayDebug("edit here")
        self.editTableProperties = EditTableProperties.EditTableProperties(self, -1, "Edit Table Properties", size=(550, 200), style=wx.DEFAULT_DIALOG_STYLE)
        self.editTableProperties.CenterOnParent()
        tmpString = self.tableListBox.GetStringSelection() # get selected item
        tmpId = int(tmpString.split(".", 1)[0]) # extract resourceID
        con = sqlite3.connect(self.TopLevelParent.database)
        cur = con.cursor()
        cur.execute("SELECT layout FROM ResourceTable WHERE resourceID = (?)", (tmpId,))
        for row in cur:
            selectedLayout = row[0].split("::")
            self.editTableProperties.tableAltText.SetValue(selectedLayout[0])
            self.editTableProperties.tableCaptionText.SetValue(selectedLayout[1])
        con.close()
        
        
        if(self.editTableProperties.ShowModal() == wx.ID_OK):
            self.layoutValue = self.editTableProperties.tableAltText.GetValue() + "::" + self.editTableProperties.tableCaptionText.GetValue()
            con = sqlite3.connect(self.TopLevelParent.database)
            cur = con.cursor()
            cur.execute("UPDATE ResourceTable SET layout = (?) WHERE resourceID = (?)", (self.layoutValue, tmpId))
            con.commit()
            con.close()
            self.TopLevelParent.currentTableDict = self.TopLevelParent.RefreshListBox(self.tableListBox, self.TopLevelParent.currentCourseID, 3, None)
            self.TopLevelParent.DisplayDebug("ok")
        else:
            self.TopLevelParent.DisplayDebug("cancel")
        
        self.editTableProperties.Destroy()
        
    def DelTable(self, event):
        tmpString = self.tableListBox.GetStringSelection()
        tmpString2 = tmpString.split(".", 1)
        con = sqlite3.connect(self.TopLevelParent.database)
        cur = con.cursor()
        cur.execute("DELETE FROM ResourceTable WHERE resourceID = (?)", (int(tmpString2[0]),))
        con.commit()
        con.close()
        self.TopLevelParent.currentTableDict = self.TopLevelParent.RefreshListBox(self.tableListBox, self.TopLevelParent.currentCourseID, 3, None)
        self.TopLevelParent.DisplayDebug("table ID " + tmpString2[0] + " deleted")
        
    def AddRow(self, event):
        if(self.tableGrid.GetSelectionBlockTopLeft() != []):
            self.tableGrid.InsertRows(self.tableGrid.GetSelectionBlockTopLeft()[0][0], (self.tableGrid.GetSelectionBlockBottomRight()[0][0] - self.tableGrid.GetSelectionBlockTopLeft()[0][0] + 1))
        else:
            self.tableGrid.InsertRows(self.tableGrid.GetGridCursorRow(), 1)
        
    def DelRow(self, event):
        if(self.tableGrid.GetSelectionBlockTopLeft() != []):
            self.tableGrid.DeleteRows(self.tableGrid.GetSelectionBlockTopLeft()[0][0], (self.tableGrid.GetSelectionBlockBottomRight()[0][0] - self.tableGrid.GetSelectionBlockTopLeft()[0][0] + 1))
        else:
            self.tableGrid.DeleteRows(self.tableGrid.GetGridCursorRow(), 1)
        
    def AddCol(self, event):
        if(self.tableGrid.GetSelectionBlockTopLeft() != []):
            self.tableGrid.InsertCols(self.tableGrid.GetSelectionBlockTopLeft()[0][1], (self.tableGrid.GetSelectionBlockBottomRight()[0][1]) - self.tableGrid.GetSelectionBlockTopLeft()[0][1] + 1)
        else:
            self.tableGrid.InsertCols(self.tableGrid.GetGridCursorCol(), 1)
        
    def DelCol(self, event):
        if(self.tableGrid.GetSelectionBlockTopLeft() != []):
            self.tableGrid.DeleteCols(self.tableGrid.GetSelectionBlockTopLeft()[0][1], (self.tableGrid.GetSelectionBlockBottomRight()[0][1] - self.tableGrid.GetSelectionBlockTopLeft()[0][1] + 1))
        else:
            self.tableGrid.DeleteCols(self.tableGrid.GetGridCursorCol(), 1)
    
    def BoldSelection(self, event):
        if(self.tableGrid.GetSelectionBlockTopLeft() != []):
            # loop to apply bold to all selected cells
            for i in range(self.tableGrid.GetSelectionBlockTopLeft()[0][0], self.tableGrid.GetSelectionBlockBottomRight()[0][0]+1):
                for j in range(self.tableGrid.GetSelectionBlockTopLeft()[0][1], self.tableGrid.GetSelectionBlockBottomRight()[0][1]+1):
                    tmpFont = self.tableGrid.GetCellFont(i, j)
                    if (self.tableGrid.GetCellFont(i, j).GetWeight() == wx.NORMAL):
                        tmpFont.SetWeight(wx.FONTWEIGHT_BOLD)
                    else:
                        tmpFont.SetWeight(wx.FONTWEIGHT_NORMAL)
                    self.tableGrid.SetCellFont(i, j, tmpFont)
        else: #apply bold to currently selected cell
            tmpFont = self.tableGrid.GetCellFont(self.tableGrid.GetGridCursorRow(), self.tableGrid.GetGridCursorCol())
            if(self.tableGrid.GetCellFont(self.tableGrid.GetGridCursorRow(), self.tableGrid.GetGridCursorCol()).GetWeight() == wx.NORMAL):
                tmpFont.SetWeight(wx.FONTWEIGHT_BOLD)
            else:
                tmpFont.SetWeight(wx.FONTWEIGHT_NORMAL)
            self.tableGrid.SetCellFont(self.tableGrid.GetGridCursorRow(), self.tableGrid.GetGridCursorCol(), tmpFont)
        self.tableGrid.Refresh() # update style immediately
    
    def SlantSelection(self, event):
        if(self.tableGrid.GetSelectionBlockTopLeft() != []):
            # "loop to apply bold to all selected cells"
            for i in range(self.tableGrid.GetSelectionBlockTopLeft()[0][0], self.tableGrid.GetSelectionBlockBottomRight()[0][0]+1):
                for j in range(self.tableGrid.GetSelectionBlockTopLeft()[0][1], self.tableGrid.GetSelectionBlockBottomRight()[0][1]+1):
                    tmpFont = self.tableGrid.GetCellFont(i, j)
                    if(self.tableGrid.GetCellFont(i, j).GetStyle() == wx.NORMAL):
                        tmpFont.SetStyle(wx.FONTSTYLE_ITALIC)
                    else:
                        tmpFont.SetStyle(wx.FONTSTYLE_NORMAL)
                    self.tableGrid.SetCellFont(i, j, tmpFont)
        else:
            tmpFont = self.tableGrid.GetCellFont(self.tableGrid.GetGridCursorRow(), self.tableGrid.GetGridCursorCol())
            if(self.tableGrid.GetCellFont(self.tableGrid.GetGridCursorRow(), self.tableGrid.GetGridCursorCol()).GetStyle() == wx.NORMAL):
                tmpFont.SetStyle(wx.FONTSTYLE_ITALIC)
            else:
                tmpFont.SetStyle(wx.FONTSTYLE_NORMAL)
            self.tableGrid.SetCellFont(self.tableGrid.GetGridCursorRow(), self.tableGrid.GetGridCursorCol(), tmpFont)
        self.tableGrid.Refresh() # update style immediately
    
    def UnderSelection(self, event):
        if(self.tableGrid.GetSelectionBlockTopLeft() != []):
            # loop to apply underline to all selected cells
            for i in range(self.tableGrid.GetSelectionBlockTopLeft()[0][0], self.tableGrid.GetSelectionBlockBottomRight()[0][0]+1):
                for j in range(self.tableGrid.GetSelectionBlockTopLeft()[0][1], self.tableGrid.GetSelectionBlockBottomRight()[0][1]+1):
                    tmpFont = self.tableGrid.GetCellFont(i, j)
                    if(self.tableGrid.GetCellFont(i, j).GetUnderlined() == False):
                        tmpFont.SetUnderlined(True)
                    else:
                        tmpFont.SetUnderlined(False)
                    self.tableGrid.SetCellFont(i, j, tmpFont)
        else:
            tmpFont = self.tableGrid.GetCellFont(self.tableGrid.GetGridCursorRow(), self.tableGrid.GetGridCursorCol())
            if(self.tableGrid.GetCellFont(self.tableGrid.GetGridCursorRow(), self.tableGrid.GetGridCursorCol()).GetUnderlined() == False):
                tmpFont.SetUnderlined(True)
            else:
                tmpFont.SetUnderlined(False)
            self.tableGrid.SetCellFont(self.tableGrid.GetGridCursorRow(), self.tableGrid.GetGridCursorCol(), tmpFont)
        self.tableGrid.Refresh() # update style immediately

    def OnSelectCell(self, event): # check cell font status.
        tmpFont= self.tableGrid.GetCellFont(event.GetRow(), event.GetCol())
        if(tmpFont.GetStyle() == wx.ITALIC):
            self.tableToolbar.ToggleTool(self.toolbar_SLANTSEL, True)
        else:
            self.tableToolbar.ToggleTool(self.toolbar_SLANTSEL, False)
        if(tmpFont.GetWeight() == wx.BOLD):
            self.tableToolbar.ToggleTool(self.toolbar_BOLDSEL, True)
        else:
            self.tableToolbar.ToggleTool(self.toolbar_BOLDSEL, False)
        if(tmpFont.GetUnderlined() == True):
            self.tableToolbar.ToggleTool(self.toolbar_UNDERSEL, True)
        else:
            self.tableToolbar.ToggleTool(self.toolbar_UNDERSEL, False)
        
        event.Skip() # allows other events to continue processing
           
    def UpdateTable(self, event):
        self.tableGrid.HideCellEditControl()
        tmpData = ""
        self.TopLevelParent.DisplayDebug("save cell values to db")
        for i in range(0, self.tableGrid.GetNumberRows()):
            if(i > 0): tmpData += "||"
            for j in range(0, self.tableGrid.GetNumberCols()):
                if(j > 0 and j < self.tableGrid.GetNumberCols()): tmpData += "::"
                tmpData += self.tableGrid.GetCellValue(i, j)
        
        self.TopLevelParent.DisplayDebug(tmpData)
        
        curItem = self.tableListBox.GetSelection()
        tmpString = self.tableListBox.GetStringSelection()
        tmpString2 = tmpString.split(".", 1)
        con = sqlite3.connect(self.TopLevelParent.database)
        cur = con.cursor()
        cur.execute("UPDATE ResourceTable SET resourceData = (?) where resourceID = (?)", (tmpData, int(tmpString2[0]),))
        con.commit()
        con.close()
        self.TopLevelParent.currentTableDict = self.TopLevelParent.RefreshListBox(self.tableListBox, self.TopLevelParent.currentCourseID, 3, None)
        self.tableListBox.SetSelection(curItem)